package gamesrv.tictactoe;


import gamesrv.gameprovider.api.GameLogic;
import gamesrv.gameprovider.api.IllegalMoveException;
import java.util.regex.*;

public class GameLogicImpl implements GameLogic {
	
	int [][] state = new int[3][3];
	boolean isFinished;
	String score;
	
	static Pattern pattern = Pattern.compile("^(\\d+),(\\d+)$");
	
	public GameLogicImpl()
	{				
		for (int i=0; i < 3; i++)
			for (int j=0; j< 3; j++)
				state[i][j] = -1;
	}

	@Override
	public String getScore() {
		// TODO Auto-generated method stub
		return score;
	}

	@Override
	public void makeMove(int user,String[] move) throws IllegalMoveException {
		if (isFinished)
			throw new IllegalMoveException();
		
		//Matcher match = pattern.matcher(move);
		//if (!match.find())
		//	throw new IllegalMoveException();
		//int x = Integer.parseInt(match.group(1));
		//int y = Integer.parseInt(match.group(2));
		int x = Integer.parseInt(move[0]);
		int y = Integer.parseInt(move[1]); 
		if (state[x][y] != -1)		
			throw new IllegalMoveException();
		
		state[x][y] = user;
		
		if (   state[x][0] == user &&  state[x][1] == user && state[x][2] == user			
			|| state[0][y] == user &&  state[1][y] == user && state[2][y] == user			
			|| state[0][0] == user &&  state[1][1] == user && state[2][2] == user
			|| state[0][2] == user &&  state[1][1] == user && state[2][0] == user
			)
		{
			score = "User " + user + " won.";
			isFinished = true;
		}
		else {
			boolean isFull = true;
			for (int i=0; i < 3; i++)
				for (int j=0; j< 3; j++)
					isFull &= state[i][j] != -1;
			if (isFull)
			{
				isFinished = true;
				score = "Tie";
			}
		}
				
	}

	@Override
	public Boolean isFinished() {
		return isFinished;
	}

	@Override
	public String[][] getSituation() {
		String[][] desc= new String[3][3];
		
		for (int i=0; i < 3; i++)
			for (int j=0; j< 3; j++)
			{
				if (state[i][j]==-1)
					desc[i][j]=" ";
				else
					desc[i][j]="" + state[i][j];
				
			}
		return desc;
		
		
		//return status;
		//		  fn(0,0) + "|" + fn(0,1) + "|" + fn(0,2) + "\r\n"
		//		+ "----\n"
		//		+ fn(1,0) + "|" + fn(1,1) + "|" + fn(1,2) + "\r\n"
		//		+ "----\n"
		//		+ fn(2,0) + "|" + fn(2,1) + "|" + fn(2,2) + "\r\n"
		//		;
	}
	
	String fn(int x,int y)
	{
		int num = state[x][y];
		if (num == -1)
			return " ";
		else
			return "" + num;
			
	}

}
